package com.android.uu.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**监听输入的价格
 * 限定只能输入小数点后指定位数；
 * 限定小数点前出现多个000开通的情况。
 * @author GuiyouZhang
 * Date：2016年1月7日 下午4:28:24
 * Email:guiyouzhang@163.com
 */
public class PriceTextChangedListener implements TextWatcher {
	
	private boolean isChanged = false;
	private EditText editText;
	private int length = 2;

	public PriceTextChangedListener(int length, EditText editText) {
		this.length = length;
		this.editText = editText;
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		if (isChanged) {// ----->如果字符未改变则返回
			return;
		}
		String str = s.toString();
		String dotBefore = "";//小数点前的整数部分
		String dotAfter = "";//小数部分
		isChanged = true;
		
		int dotIndex = str.indexOf(".");//小数点的位置
		if (dotIndex > 0) {//有小数点
			dotBefore = str.substring(0, dotIndex);
			dotAfter = str.substring(dotIndex + 1);
		}else {//没有小数点
			dotBefore = str;
		}
		//删除整数部分开头的0
		if (dotBefore.length() != 1) {
			while (dotBefore.startsWith("0")) {
				dotBefore = dotBefore.substring(1);
			}
		}
		//删除小数点后两位之后的数字
		if (dotAfter.length() > 2) {
			dotAfter = dotAfter.substring(0, 2);
		}
		//重新组合字符串
		if (dotIndex > 0) {//有小数点
			str = dotBefore+"."+dotAfter;
		}else if (dotIndex == 0) {//如果输入的内容以小数点开头，就去掉小数点
			str = "";
		}else {//没有小数点
			str = dotBefore;
		}
        int selection = editText.getSelectionEnd();
		editText.setText(str);
		// 设处理光标
		int size = editText.length();
		if (selection< size)
			editText.setSelection(selection);
		else
			editText.setSelection(size);
		isChanged = false;
	}

}
